package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 杨林
 * @create 2022-09-22 10:20 星期四
 * description:
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {

    @Reference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(Model model, @PathVariable Long houseId,@PathVariable Long type){
        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);
        return "houseImage/upload";
    }

    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId, @PathVariable Integer type,
                               @RequestParam("file") MultipartFile[] files) throws IOException {
        if (files.length > 0){
            for (MultipartFile file : files) {

                //使用UUID防止同名文件覆盖
                String uuid = UUID.randomUUID().toString();
                String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String newFileName = uuid + substring;

                //上传图片
                QiniuUtil.upload2Qiniu(file.getBytes(), newFileName);

                //七牛云空间的url
                String Url = "http://riiaaev13.hb-bkt.clouddn.com/" + newFileName;

                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setType(type);
                houseImage.setImageName(newFileName);
                houseImage.setImageUrl(Url);
                houseImageService.insert(houseImage);
            }
        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id){

        //根据id获取houseImage
        HouseImage houseImage = houseImageService.getById(id);

        //删除七牛云上的数据
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());

        //删除数据库中的数据
        houseImageService.delete(id);

        return "redirect:/house/{houseId}";
    }

}
